<?php
/**
 * GolfScore helper functions
 *
 * @package GolfScore
 */

/**
 * Prepare the add/edit form variables
 *
 * @param ElggObject $golfscore golfscore object.
 * @return array
 */
function golfscore_prepare_form_vars($golfscore = null) {
	$values = array(
		'title' => get_input('title', ''), // bookmarklet support
		'address' => get_input('address', ''),
		'description' => '',
		'access_id' => ACCESS_DEFAULT,
		'tags' => '',
		'shares' => array(),
		'container_guid' => elgg_get_page_owner_guid(),
		'guid' => null,
		'entity' => $golfscore,
	);

	if ($golfscore) {
		foreach (array_keys($values) as $field) {
			if (isset($golfscore->$field)) {
				$values[$field] = $golfscore->$field;
			}
		}
	}

	if (elgg_is_sticky_form('golfscore')) {
		$sticky_values = elgg_get_sticky_values('golfscore');
		foreach ($sticky_values as $key => $value) {
			$values[$key] = $value;
		}
	}

	elgg_clear_sticky_form('golfscore');

	return $values;
}

function elgg_list_golf_course(array $options = array()) {
	global $autofeed;
	$autofeed = true;

	$defaults = array(
			'offset'     => (int) max(get_input('offset', 0), 0),
			'limit'      => (int) max(get_input('limit', 50), 0),
			'pagination' => TRUE,
			'list_class' => 'elgg-list-river elgg-river', // @todo remove elgg-river in Elgg 1.9
	);

	$options = array_merge($defaults, $options);

	$options['count'] = TRUE;
	$count = elgg_get_golf_course($options);

	$options['count'] = FALSE;
	$items = elgg_get_golf_course($options);

	$options['count'] = $count;
	$options['items'] = $items;
	return elgg_view('page/components/list', $options);
}

/**
 * Get river items
 *
 * @note If using types and subtypes in a query, they are joined with an AND.
 *
 * @param array $options Parameters
 *
 * @return array|int
 * @since 1.8.0
 */
function elgg_get_golf_course(array $options = array()) {
	global $CONFIG;
	$defaults = array(
			'golf_course_id'           	=> ELGG_ENTITIES_ANY_VALUE,
			'course_name'	       		=> ELGG_ENTITIES_ANY_VALUE,
				
			'gold_course_rating'        => ELGG_ENTITIES_ANY_VALUE,
			'blue_course_rating'       	=> ELGG_ENTITIES_ANY_VALUE,
			'white_course_rating'       => ELGG_ENTITIES_ANY_VALUE,
			'red_white_course_rating'	=> ELGG_ENTITIES_ANY_VALUE,

			'gold_course_slope'	        => ELGG_ENTITIES_ANY_VALUE,
			'blue_course_slope'         => ELGG_ENTITIES_ANY_VALUE,
			'white_course_slope'   		=> ELGG_ENTITIES_ANY_VALUE,
			'red_course_slope'   		=> ELGG_ENTITIES_ANY_VALUE,

			'par_total'	   				=> ELGG_ENTITIES_ANY_VALUE,
				
			'gold_total'	   			=> ELGG_ENTITIES_ANY_VALUE,
			'blue_total'	   			=> ELGG_ENTITIES_ANY_VALUE,
			'white_total'	   			=> ELGG_ENTITIES_ANY_VALUE,
			'red_total'	   				=> ELGG_ENTITIES_ANY_VALUE,
				
			'gold_tee_name'	  		 	=> ELGG_ENTITIES_ANY_VALUE,
			'blue_tee_name'	   			=> ELGG_ENTITIES_ANY_VALUE,
			'white_tee_name'	   		=> ELGG_ENTITIES_ANY_VALUE,
			'red_tee_name'	   			=> ELGG_ENTITIES_ANY_VALUE,
				
			'active_flg'	   			=> ELGG_ENTITIES_ANY_VALUE,

			'limit'                		=> 20,
			'offset'               		=> 0,
			'count'                		=> FALSE,

			'order_by'             		=> 'gc.golf_course_id',
			'group_by'             		=> ELGG_ENTITIES_ANY_VALUE,

			'wheres'               		=> array(),
			'joins'                		=> array(),
	);

	$options = array_merge($defaults, $options);

	$wheres = array();

	if ($options['golf_course_id']) {
		$wheres[] = "gc.golf_course_id = {$options['golf_course_id']}";
	}

	// see if any functions failed
	// remove empty strings on successful functions
	foreach ($wheres as $i => $where) {
		if ($where === FALSE) {
			return FALSE;
		} elseif (empty($where)) {
			unset($wheres[$i]);
		}
	}

	// remove identical where clauses
	$wheres = array_unique($wheres);

	if (!$options['count']) {
		$query = "SELECT DISTINCT gc.* FROM {$CONFIG->dbprefix}golf_course gc ";
	} else {
		$query = "SELECT count(DISTINCT gc.golf_course_id) as total FROM {$CONFIG->dbprefix}golf_course gc ";
	}

	// add wheres
	if ($wheres) {
		$query .= ' WHERE ';
		foreach ($wheres as $w) {
			$query .= " $w AND ";
		}
		$query .= "1=1";
	}

	if (!$options['count']) {
		$options['order_by'] = sanitise_string($options['order_by']);
		$query .= " ORDER BY {$options['order_by']}";

		if ($options['limit']) {
			$limit = sanitise_int($options['limit']);
			$offset = sanitise_int($options['offset'], false);
			$query .= " LIMIT $offset, $limit";
		}

		$river_items = get_data($query, 'elgg_row_to_elgg_golf_course_item');

		return $river_items;
	} else {
		$total = get_data_row($query);
		return (int)$total->total;
	}
}

function elgg_row_to_elgg_golf_course_item($row) {
	if (!($row instanceof stdClass)) {
		return NULL;
	}

	return new ElggGolfCourseItem($row);
}

function elgg_get_golf_course_card(array $options = array()) {
	global $CONFIG;
	$defaults = array(
			'golf_course_card_id' 		=> ELGG_ENTITIES_ANY_VALUE,
			'golf_course_id'	      	=> ELGG_ENTITIES_ANY_VALUE,
			'hole'        				=> ELGG_ENTITIES_ANY_VALUE,
				
			'gold_tee_distance'       	=> ELGG_ENTITIES_ANY_VALUE,
			'blue_tee_distance'       	=> ELGG_ENTITIES_ANY_VALUE,
			'white_tee_distance'		=> ELGG_ENTITIES_ANY_VALUE,
			'red_tee_distance'	        => ELGG_ENTITIES_ANY_VALUE,
				
			'par'         				=> ELGG_ENTITIES_ANY_VALUE,

			'limit'                		=> 20,
			'offset'               		=> 0,
			'count'                		=> FALSE,

			'order_by'             		=> 'gcc.hole',
			'group_by'             		=> ELGG_ENTITIES_ANY_VALUE,

			'wheres'               		=> array(),
			'joins'                		=> array(),
	);

	$options = array_merge($defaults, $options);

	$wheres = array();

	if ($options['golf_course_id']) {
		$wheres[] = "gcc.golf_course_id = {$options['golf_course_id']}";
	}
	
	if ($options['hole']) {
		$wheres[] = "gcc.hole = {$options['hole']}";
	}
	
	if ($options['golf_course_card_id']) {
		$wheres[] = "gcc.golf_course_card_id = {$options['golf_course_card_id']}";
	}
	// see if any functions failed
	// remove empty strings on successful functions
	foreach ($wheres as $i => $where) {
		if ($where === FALSE) {
			return FALSE;
		} elseif (empty($where)) {
			unset($wheres[$i]);
		}
	}

	// remove identical where clauses
	$wheres = array_unique($wheres);

	if (!$options['count']) {
		$query = "SELECT DISTINCT gcc.* FROM {$CONFIG->dbprefix}golf_course_card gcc ";
	} else {
		$query = "SELECT count(DISTINCT gcc.golf_course_card_id) as total FROM {$CONFIG->dbprefix}golf_course_card gcc ";
	}

	// add wheres
	if ($wheres) {
		$query .= ' WHERE ';
		foreach ($wheres as $w) {
			$query .= " $w AND ";
		}
		$query .= "1=1";
	}

	if (!$options['count']) {
		$options['order_by'] = sanitise_string($options['order_by']);
		$query .= " ORDER BY {$options['order_by']}";

		if ($options['limit']) {
			$limit = sanitise_int($options['limit']);
			$offset = sanitise_int($options['offset'], false);
			$query .= " LIMIT $offset, $limit";
		}

		$river_items = get_data($query, 'elgg_row_to_elgg_golf_course_card_item');

		return $river_items;
	} else {
		$total = get_data_row($query);
		return (int)$total->total;
	}
}

function elgg_row_to_elgg_golf_course_card_item($row) {
	if (!($row instanceof stdClass)) {
		return NULL;
	}

	return new ElggGolfCourseCardItem($row);
}

function elgg_get_golf_score_detail(array $options = array()) {
	global $CONFIG;
	$defaults = array(
			'golf_score_detail_id' 		=> ELGG_ENTITIES_ANY_VALUE,
			'golf_score_id'	      	=> ELGG_ENTITIES_ANY_VALUE,
			'hole'        				=> ELGG_ENTITIES_ANY_VALUE,

			'score'       	=> ELGG_ENTITIES_ANY_VALUE,
			'esc_adjustment_score'       	=> ELGG_ENTITIES_ANY_VALUE,

			'limit'                		=> 20,
			'offset'               		=> 0,
			'count'                		=> FALSE,

			'order_by'             		=> 'gsd.hole',
			'group_by'             		=> ELGG_ENTITIES_ANY_VALUE,

			'wheres'               		=> array(),
			'joins'                		=> array(),
	);

	$options = array_merge($defaults, $options);

	$wheres = array();

	if ($options['golf_score_id']) {
		$wheres[] = "gsd.golf_score_id = {$options['golf_score_id']}";
	}
	
	if ($options['hole']) {
		$wheres[] = "gsd.hole = {$options['hole']}";
	}

	// see if any functions failed
	// remove empty strings on successful functions
	foreach ($wheres as $i => $where) {
		if ($where === FALSE) {
			return FALSE;
		} elseif (empty($where)) {
			unset($wheres[$i]);
		}
	}

	// remove identical where clauses
	$wheres = array_unique($wheres);

	if (!$options['count']) {
		$query = "SELECT DISTINCT gsd.* FROM {$CONFIG->dbprefix}golf_score_detail gsd ";
	} else {
		$query = "SELECT count(DISTINCT gsd.golf_score_detail_id) as total FROM {$CONFIG->dbprefix}golf_score_detail gsd ";
	}

	// add wheres
	if ($wheres) {
		$query .= ' WHERE ';
		foreach ($wheres as $w) {
			$query .= " $w AND ";
		}
		$query .= "1=1";
	}

	if (!$options['count']) {
		$options['order_by'] = sanitise_string($options['order_by']);
		$query .= " ORDER BY {$options['order_by']}";

		if ($options['limit']) {
			$limit = sanitise_int($options['limit']);
			$offset = sanitise_int($options['offset'], false);
			$query .= " LIMIT $offset, $limit";
		}

		$river_items = get_data($query, 'elgg_row_to_elgg_golf_score_detail_item');

		return $river_items;
	} else {
		$total = get_data_row($query);
		return (int)$total->total;
	}
}

function elgg_row_to_elgg_golf_score_detail_item($row) {
	if (!($row instanceof stdClass)) {
		return NULL;
	}

	return new ElggGolfScoreDetailItem($row);
}

function elgg_list_golf_score(array $options = array()) {
	global $autofeed;
	$autofeed = true;
	
	$defaults = array(
			'offset'     => (int) max(get_input('offset', 0), 0),
			'limit'      => (int) max(get_input('limit', 10), 0),
			'golf_course_id' => get_input('golf_course_id'),
			'active_flg' => 1,
			'on_sidebar' => false,
			'pagination' => TRUE,
			'full_view' => true,
			'pagination' => true,
			'list_type' => 'list',
			'list_type_toggle' => false,
			'header_list_class' => 'elgg-header-list',
			'list_class' => 'elgg-golfscore-list',
			'item_class' => 'elgg-item',
	);
	
	$options = array_merge($defaults, $options);
	
	$options['count'] = TRUE;
	$count = elgg_get_golf_score($options);
	if (!$count || $count < 1) {
		return elgg_echo('golf_score:none');
	}

	$options['count'] = FALSE;
	$items = elgg_get_golf_score($options);

	$options['count'] = $count;
	$options['items'] = $items;

// 	$options['list_class'] = 'elgg-river';
// 	$options['item_class'] = 'elgg-item';
	
	if(!$options['on_sidebar']) {
		$options['header_list_class'] = 'elgg-header-list';
		
		$options['headers'] = array(
				array('text' => 'Date', 'class' => 'elgg-header-list-item-date'),
				array('text' => 'Course', 'class' => 'elgg-header-list-item-course'),
				array('text' => 'Score', 'class' => 'elgg-header-list-item-score')
		);
		return elgg_view('golfscore/list_header', $options) . elgg_view('golfscore/list', $options);
	} else {
		return elgg_view('golfscore/list', $options);
	}
}

function elgg_view_golf_score(array $options = array()) {
	return elgg_view('golfscore/list_header', $options);
}

function elgg_get_golf_score(array $options = array()) {
	global $CONFIG;

	$user_guid = elgg_get_logged_in_user_guid();

	$defaults = array(
			'golf_score_id'           		=> ELGG_ENTITIES_ANY_VALUE,
			'golf_course_id'	       		=> ELGG_ENTITIES_ANY_VALUE,
			'course_name'	       			=> ELGG_ENTITIES_ANY_VALUE,
			'user_entity_id'        		=> ELGG_ENTITIES_ANY_VALUE,
				
			'tee'       					=> ELGG_ENTITIES_ANY_VALUE,
			'total_score'					=> ELGG_ENTITIES_ANY_VALUE,

			'esc_adjustment_total_score'	=> ELGG_ENTITIES_ANY_VALUE,
				
			'course_rating'	    			=> ELGG_ENTITIES_ANY_VALUE,
			'course_slope'					=> ELGG_ENTITIES_ANY_VALUE,
			
			'holes_played'					=> ELGG_ENTITIES_ANY_VALUE,
				
			'input_date'   					=> ELGG_ENTITIES_ANY_VALUE,
			'update_date'   				=> ELGG_ENTITIES_ANY_VALUE,
			
			'active_flg'   					=> ELGG_ENTITIES_ANY_VALUE,
				
			'user_entity_ids'   			=> ELGG_ENTITIES_ANY_VALUE,

			'limit'                			=> 50,
			'offset'               			=> 0,
			'count'                			=> FALSE,
			'average'                		=> FALSE,
			'average_column'                => '',

			'order_by'             			=> 'gs.input_date desc, gs.golf_score_id desc',
			'group_by'             			=> ELGG_ENTITIES_ANY_VALUE,

			'wheres'               			=> array(),
			'joins'                			=> array(),
	);

	$options = array_merge($defaults, $options);
	$wheres = array();
	if ($options['golf_score_id']) {
		$wheres[] = "gs.golf_score_id = {$options['golf_score_id']}";
	}
	if($options['user_entity_ids']) {
		$condition = '';
		foreach ($options['user_entity_ids'] as $id) {
			$condition .= $id . ',';
		}
		$condition = substr($condition, 0, strlen($condition) - 1);
		$wheres[] = "gs.user_entity_id IN ({$condition})";
	} else {
		if ($options['user_entity_id']) {
			$wheres[] = "gs.user_entity_id = {$options['user_entity_id']}";
		}
// 		 else {
// 			$wheres[] = "gs.user_entity_id = {$user_guid}";
// 		}
	}
	if ($options['golf_course_id']) {
		$wheres[] = "gs.golf_course_id = {$options['golf_course_id']}";
	}
	if ($options['active_flg']) {
		$wheres[] = "gs.active_flg = {$options['active_flg']}";
	}
	if ($options['holes_played']) {
		$wheres[] = "gs.holes_played = {$options['holes_played']}";
	}
	
	// see if any functions failed
	// remove empty strings on successful functions
	foreach ($wheres as $i => $where) {
		if ($where === FALSE) {
			return FALSE;
		} elseif (empty($where)) {
			unset($wheres[$i]);
		}
	}

	// remove identical where clauses
	$wheres = array_unique($wheres);

	$joins = "INNER JOIN {$CONFIG->dbprefix}golf_course gc ON gs.golf_course_id = gc.golf_course_id ";
	$joins .= "INNER JOIN {$CONFIG->dbprefix}users_entity ue ON ue.guid = gs.user_entity_id ";

	if (!$options['count']) {
		if (!$options['average']) {
			$query = "SELECT DISTINCT gs.*, gc.course_name, ue.name AS user_full_name, ue.username AS user_name FROM {$CONFIG->dbprefix}golf_score gs " . $joins;
		} else {
			$query = "SELECT AVG(" . $options['average_column'] . ") as total FROM {$CONFIG->dbprefix}golf_score gs " . $joins;
		}
	} else {
		$query = "SELECT count(DISTINCT gs.golf_score_id) as total FROM {$CONFIG->dbprefix}golf_score gs " . $joins;
	}

	// add wheres
	if ($wheres) {
		$query .= ' WHERE ';
		foreach ($wheres as $w) {
			$query .= " $w AND ";
		}
		$query .= "1=1";
	}

	if (!$options['count']) {
		if (!$options['average']) {
			$options['order_by'] = sanitise_string($options['order_by']);
			$query .= " ORDER BY {$options['order_by']}";
	
			if ($options['limit']) {
				$limit = sanitise_int($options['limit']);
				$offset = sanitise_int($options['offset'], false);
				$query .= " LIMIT $offset, $limit";
			}
	
			$river_items = get_data($query, 'elgg_row_to_elgg_golf_score_item');
	
			return $river_items;
		} else {
			if ($options['limit']) {
				$limit = sanitise_int($options['limit']);
				$offset = sanitise_int($options['offset'], false);
				$query .= " LIMIT $offset, $limit";
			}
			$total = get_data_row($query);
			return (float)$total->total;
		}
	} else {
		$total = get_data_row($query);
		return (int)$total->total;
	}
}

function elgg_row_to_elgg_golf_score_item($row) {
	if (!($row instanceof stdClass)) {
		return NULL;
	}

	return new ElggGolfScoreItem($row);
}

function elgg_get_golf_handicap(array $options = array()) {
	global $CONFIG;
	$defaults = array(
			'golf_handicap_id'		=> ELGG_ENTITIES_ANY_VALUE,
			'user_entity_id'       	=> ELGG_ENTITIES_ANY_VALUE,
			'handicap_date'       	=> ELGG_ENTITIES_ANY_VALUE,
			'handicap_index'		=> ELGG_ENTITIES_ANY_VALUE,

			'limit'                	=> 20,
			'offset'               	=> 0,
			'count'                	=> FALSE,

			'order_by'             	=> 'gh.handicap_date',
			'group_by'             	=> ELGG_ENTITIES_ANY_VALUE,

			'wheres'               	=> array(),
			'joins'                	=> array(),
	);

	$options = array_merge($defaults, $options);

	$wheres = array();

	if ($options['user_entity_id']) {
		$wheres[] = "gh.user_entity_id = {$options['user_entity_id']}";
	}

	// see if any functions failed
	// remove empty strings on successful functions
	foreach ($wheres as $i => $where) {
		if ($where === FALSE) {
			return FALSE;
		} elseif (empty($where)) {
			unset($wheres[$i]);
		}
	}

	// remove identical where clauses
	$wheres = array_unique($wheres);

	if (!$options['count']) {
		$query = "SELECT DISTINCT gh.* FROM {$CONFIG->dbprefix}golf_handicap gh ";
	} else {
		$query = "SELECT count(DISTINCT gh.golf_handicap_id) as total FROM {$CONFIG->dbprefix}golf_handicap gh ";
	}

	// add wheres
	if ($wheres) {
		$query .= ' WHERE ';
		foreach ($wheres as $w) {
			$query .= " $w AND ";
		}
		$query .= "1=1";
	}

	if (!$options['count']) {
		$options['order_by'] = sanitise_string($options['order_by']);
		$query .= " ORDER BY {$options['order_by']}";

		if ($options['limit']) {
			$limit = sanitise_int($options['limit']);
			$offset = sanitise_int($options['offset'], false);
			$query .= " LIMIT $offset, $limit";
		}

		$river_items = get_data($query, 'elgg_row_to_elgg_golf_handicap_item');

		return $river_items;
	} else {
		$total = get_data_row($query);
		return (int)$total->total;
	}
}

function elgg_row_to_elgg_golf_handicap_item($row) {
	if (!($row instanceof stdClass)) {
		return NULL;
	}

	return new ElggGolfHandicapItem($row);
}

function save_golf_score($golf_score) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}
	$input_date = mysql_real_escape_string($golf_score->input_date);
	$update_date = mysql_real_escape_string($golf_score->update_date);
	if($golf_score->golf_score_id) {
		return update_data("UPDATE {$CONFIG->dbprefix}golf_score
		SET golf_course_id = $golf_score->golf_course_id, tee = '$golf_score->tee', total_score = $golf_score->total_score, 
		esc_adjustment_total_score = $golf_score->esc_adjustment_total_score, update_date = '$update_date',
		course_rating = $golf_score->course_rating, course_slope = $golf_score->course_slope, holes_played = $golf_score->holes_played, score_type = $golf_score->score_type 
		WHERE golf_score_id = $golf_score->golf_score_id");
	} else {
		return insert_data("INSERT into {$CONFIG->dbprefix}golf_score
		(golf_course_id, user_entity_id, tee, total_score, esc_adjustment_total_score, input_date, update_date, active_flg, course_rating, course_slope, holes_played, score_type)
		values
		($golf_score->golf_course_id,$golf_score->user_entity_id, '$golf_score->tee', $golf_score->total_score, $golf_score->esc_adjustment_total_score,
		'$input_date', '$update_date', $golf_score->active_flg, $golf_score->course_rating, $golf_score->course_slope, $golf_score->holes_played, $golf_score->score_type)");
	}
}

function save_golf_score_detail($golf_score_detail) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}

	return insert_data("INSERT into {$CONFIG->dbprefix}golf_score_detail
	(golf_score_id, hole, score, esc_adjustment_score)
	values
	($golf_score_detail->golf_score_id, $golf_score_detail->hole, $golf_score_detail->score, $golf_score_detail->esc_adjustment_score)");
}

function delete_golf_score_detail($golf_score_id) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}

	return delete_data("DELETE FROM {$CONFIG->dbprefix}golf_score_detail WHERE golf_score_id = $golf_score_id");
}

function save_golf_handicap($golf_handicap, $old_handicap_index) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}
	if(!isset($golf_handicap->golf_handicap_id)) {
		return insert_data("INSERT into {$CONFIG->dbprefix}golf_handicap
		(user_entity_id, handicap_date, handicap_index)
		values
		($golf_handicap->user_entity_id, '$golf_handicap->handicap_date', $golf_handicap->handicap_index)");
	} else {
		if(update_data("UPDATE {$CONFIG->dbprefix}golf_handicap
		SET handicap_date = '$golf_handicap->handicap_date', handicap_index = $golf_handicap->handicap_index
		WHERE golf_handicap_id = $golf_handicap->golf_handicap_id")) {
			
		$current_date = date("Y-m-d H:i:s");
		insert_data("INSERT into {$CONFIG->dbprefix}golf_handicap_history
		(user_entity_id, handicap_date, handicap_index)
		values
		($golf_handicap->user_entity_id, '$current_date', $old_handicap_index)");
		return true;
		}
		return false;
	}
}

function delete_golf_handicap_by_user($user_entity_id) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}

	return delete_data("DELETE FROM {$CONFIG->dbprefix}golf_handicap WHERE user_entity_id = $user_entity_id");
}

function delete_golf_score($golf_score_id) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}
	return update_data("UPDATE {$CONFIG->dbprefix}golf_score
		SET active_flg = 0 
		WHERE golf_score_id = $golf_score_id");
}

function golfscore_post($user,$score,$golf_course) {
	$body = elgg_view('output/url', array(
			'href' => "profile/$user->username",
			'text' => $user->name,
			'is_trusted' => true,
	));
	$body .= ' shot an ';
	$body .= elgg_view('output/url', array(
			'href' => "golfscore/view?golf_score_id=$score->golf_score_id",
			'text' => $score->total_score,
			'is_trusted' => true,
	));
	$body .= " at ";
	$body .= elgg_view('output/url', array(
			'href' => "golfscore/all?golf_course_id=$golf_course->golf_course_id",
			'text' => $golf_course->course_name,
			'is_trusted' => true,
	));
	$body .= " Course";
	$access_id = ACCESS_PUBLIC;
	$method = 'site';
	
	$post = new ElggObject();
	
	$post->subtype = "thewire";
	$post->owner_guid = $user->guid;
	$post->access_id = $access_id;
	
	// only 200 characters allowed
// 	$text = elgg_substr($body, 0, 200);
	$text = $body;
	
	// no html tags allowed so we escape
	$post->description = $text;//htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
	
	$post->method = $method; //method: site, email, api, ...
	
	$tags = thewire_get_hashtags($text);
	if ($tags) {
		$post->tags = $tags;
	}
	
	$guid = $post->save();
	
	// first post in this thread
	$post->wire_thread = $guid;
	
	if ($guid) {
		add_to_river('river/object/thewire/create', 'create', $post->owner_guid, $post->guid);
	
		// let other plugins know we are setting a user status
		$params = array(
				'entity' => $post,
				'user' => $post->getOwnerEntity(),
				'message' => $post->description,
				'url' => $post->getURL(),
				'origin' => 'thewire',
		);
		elgg_trigger_plugin_hook('status', 'user', $params);
	}
	
	//elgg_trigger_plugin_hook('thewire','post', array('body' => $body), false);
}

function elgg_golfscore_recalculate_handicap($golf_handicap, $user_giud, $current_date) {
	if(!isset($golf_handicap)) {
		$golf_handicaps = elgg_get_golf_handicap(array('user_entity_id' => $user_giud));
		if(isset($golf_handicaps) && count($golf_handicaps) >= 1) {
			$golf_handicap = $golf_handicaps[0];
		}
	}
	if(!isset($current_date)) {
		$current_date = date("Y-m-d H:i:s");
	}
	$golf_scores = elgg_get_golf_score(array(
			'active_flg' => 1,
			'holes_played' => 18,
			'limit' => 20, 
			'order_by' => 'gs.esc_adjustment_total_score'
		));
	$new_handicap_index = elgg_golfscore_get_handicap_index($golf_scores);
	if($new_handicap_index >= 0) {
		if(isset($golf_handicap)) {
			$old_handicap_index = $golf_handicap->handicap_index;
			$golf_handicap->handicap_date = $current_date;
			$golf_handicap->handicap_index = $new_handicap_index;
			save_golf_handicap($golf_handicap, $old_handicap_index);
		} else {
			$golf_handicap = new ElggGolfHandicapItem();
			$golf_handicap->user_entity_id = $user_giud;
			$golf_handicap->handicap_date = $current_date;
			$golf_handicap->handicap_index = $new_handicap_index;
			save_golf_handicap($golf_handicap);
		}
	} else {
		delete_golf_handicap_by_user($user_giud);
	}
}

function elgg_golfscore_get_handicap_index($scores) {
	$best_scores = elgg_golfscore_get_best_score($scores);
	$decimal_score_total = 0;
	foreach ($best_scores as $best_score) {
		$decimal_score = elgg_golfscore_get_decimal_score($best_score->esc_adjustment_total_score,$best_score->course_rating,$best_score->course_slope);
		$decimal_score_total += $decimal_score;
	}
	if(count($best_scores) == 0) {
		return -1;
	}
	$handicap_index = $decimal_score_total / count($best_scores) * 0.96;
	$handicap_index = elgg_golfscore_round($handicap_index, 2);
	return $handicap_index;
}

function elgg_golfscore_get_best_score($scores) {
	$best_scores = array();
	$count = count($scores);
	if(!isset($scores) || $count < 5){
		return $best_scores;
	}
	$sorted_scores = sort_scores($scores);
	if($count == 5 || $count == 6) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 1));
	} else if($count == 7 || $count == 8) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 2));
	} else if($count == 9 || $count == 10) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 3));
	} else if($count == 11 || $count == 12) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 4));
	} else if($count == 13 || $count == 14) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 5));
	} else if($count == 15 || $count == 16) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 6));
	} else if($count == 17) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 7));
	} else if($count == 18) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 8));
	} else if($count == 19) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 9));
	} else if($count >= 20) {
		$best_scores = array_merge($best_scores, array_slice($sorted_scores, 0, 10));
	}
	return $best_scores;
}

function sort_scores($scores) {
	$sorted_scores = array();
	$count = count($scores);
	if(!isset($scores)){
		return $sorted_scores;
	}
	foreach ($scores as $score) {
		$inserted = false;
		for($i = 0; $i < count($sorted_scores); $i++) {
			$sorted_score = $sorted_scores[$i];
			$decimal_score = elgg_golfscore_get_decimal_score($score->esc_adjustment_total_score,$score->course_rating,$score->course_slope);
			$sorted_decimal_score = elgg_golfscore_get_decimal_score($sorted_score->esc_adjustment_total_score,$sorted_score->course_rating,$sorted_score->course_slope);
			if($sorted_decimal_score > $decimal_score) {
				insertArray($sorted_scores, $score, $i);
				$inserted = true;
				break;;
			}
		}
		if(!$inserted) {
			insertArray($sorted_scores, $score, count($sorted_scores));
		}
	}
	return $sorted_scores;
}

function insertArray(&$arr, $value, $index){
	$lengh = count($arr);
	if($index<0||$index>$lengh)
		return;

	for($i=$lengh; $i>$index; $i--){
		$arr[$i] = $arr[$i-1];
	}

	$arr[$index] = $value;
}

function elgg_golfscore_get_escadjustment_score($handicap_index,$tee,$course,$course_cards,$score_total,$score_map) {
	if(!isset($handicap_index)) {
		$handicap_index = 0;
	}
	$course_rating = elgg_golfscore_get_course_rating($tee,$course);
	$course_slope = elgg_golfscore_get_course_slope($tee,$course);
	$handicap = elgg_golfscore_get_course_handicap($handicap_index,$course_slope);
	$par_map = array();
	$escadjustment_score_total = 0;
	foreach ($course_cards as $course_card) {
		$par_map['' . $course_card->hole] = $course_card->par;
		$escadjustment_score = elgg_golfscore_escadjustment_score($handicap,$par_map[$i],null);
		$escadjustment_score_total += $escadjustment_score;
	}
	if(count($score_map) == 18) {
		$escadjustment_score_total = 0;
		for ($i = 1; $i <= 18; $i++) {
			$escadjustment_score = elgg_golfscore_escadjustment_score($handicap,$par_map[$i],$score_map[$i]);
			$escadjustment_score_total += $escadjustment_score;
		}
	}
	if(isset($score_total) && $escadjustment_score_total > $score_total) {
		return $score_total;
	} else {
		return $escadjustment_score_total;
	}
}

function elgg_golfscore_get_escadjustment_score_map($handicap_index,$tee,$course,$course_cards,$score_total,$score_map) {
	if(!isset($handicap_index)) {
		$handicap_index = 0;
	}
	$course_rating = elgg_golfscore_get_course_rating($tee,$course);
	$course_slope = elgg_golfscore_get_course_slope($tee,$course);
	$handicap = elgg_golfscore_get_course_handicap($handicap_index,$course_slope);
	$par_map = array();
	foreach ($course_cards as $course_card) {
		$par_map['' . $course_card->hole] = $course_card->par;
	}
	$escadjustment_score_map = array();
	for ($i = 1; $i <= 18; $i++) {
		$escadjustment_score = elgg_golfscore_escadjustment_score($handicap,$par_map[$i],$score_map[$i]);
		$escadjustment_score_map[$i] = $escadjustment_score;
	}
	return $escadjustment_score_map;
}

function elgg_golfscore_escadjustment_score($handicap,$par,$score) {
	$escadjustment_score = -1;
	if($handicap >= 0 && $handicap < 9) {
		if(!isset($score)) {
			return $par + 2;
		} else {
			if($score > $par + 2) {
				return $par + 2;
			} else {
				return $score;
			}
		}
	} else if($handicap >= 10 && $handicap < 19) {
		if(!isset($score)) {
			return 7;
		} else {
			if($score > 7) {
				return 7;
			} else {
				return $score;
			}
		}
	} else if($handicap >= 20 && $handicap < 29) {
		if(!isset($score)) {
			return 8;
		} else {
			if($score > 8) {
				return 8;
			} else {
				return $score;
			}
		}
	} else if($handicap >= 30 && $handicap < 39) {
		if(!isset($score)) {
			return 9;
		} else {
			if($score > 9) {
				return 9;
			} else {
				return $score;
			}
		}
	} else {
		if(!isset($score)) {
			return 10;
		} else {
			if($score > 10) {
				return 10;
			} else {
				return $score;
			}
		}
	}
}

function elgg_golfscore_get_course_handicap($handicap_index,$course_slope) {
	return elgg_golfscore_round($handicap_index * $course_slope / 113, 3);
}

function elgg_golfscore_get_decimal_score($escadjustment_score,$course_rating,$course_slope) {
	return elgg_golfscore_round(($escadjustment_score - $course_rating) * 113 / $course_slope, 1);
}

function elgg_golfscore_get_course_rating($tee,$course) {
	if($tee == 'gold') {
		return $course->gold_course_rating;
	} else if($tee == 'blue') {
		return $course->blue_course_rating;
	} else if($tee == 'white') {
		return $course->white_course_rating;
	} else if($tee == 'red') {
		return $course->red_course_rating;
	}
	return -1;
}

function elgg_golfscore_get_course_slope($tee,$course) {
	if($tee == 'gold') {
		return $course->gold_course_slope;
	} else if($tee == 'blue') {
		return $course->blue_course_slope;
	} else if($tee == 'white') {
		return $course->white_course_slope;
	} else if($tee == 'red') {
		return $course->red_course_slope;
	}
	return -1;
}

function elgg_golfscore_round($value, $type) {
	if(strpos('' . $value, '.') >= 0) {
		$value_1 = substr('' . $value, 0, strpos('' . $value, '.'));
		$value_2 = substr('' . $value, strpos('' . $value, '.') + 1, strlen('' . $value));
		if($type == 1) {
			if(strlen($value_2) == 1) {
				return $value;
			} else {
				$value_21 = substr('' . $value_2, 0, 1);
				$value_22 = substr('' . $value_2, 1, 2);
				if(((int)$value_22) >= 5) {
					$value_21 = ((int)$value_21) + 1;
				}
				return (float)($value_1 . '.' . $value_21);
			}
		} else if($type == 2) {
			if(strlen($value_2) == 1) {
				return $value;
			} else {
				$value_21 = substr('' . $value_2, 0, 1);
				return (float)($value_1 . '.' . $value_21);
			}
		} else if($type == 3) {
			$value_21 = substr('' . $value_2, 0, 1);
			if(((int)$value_21) >= 5) {
				return ((int)$value_1) + 1;
			} else {
				return (int)$value_1;
			}
		}
	} else {
		return $value;
	}
}

function getIntegerValue($value) {
	if(!isset($value)) {
		return null;
	}
	$_int = (int)$value;
	if(($_int . '') == ($value . '')) {
		return (int)$value;
	}
	return null;
}

function getTeeName($tee,$course) {
	$tee = $tee . '';
	if($tee == 'gold') {
		return $course->gold_tee_name;
	} else if($tee == 'blue') {
		return $course->blue_tee_name;
	} else if($tee == 'white') {
		return $course->white_tee_name;
	} else if($tee == 'red') {
		return $course->red_tee_name;
	}
	return '';
}

function getTeeAttributes($tee,$golf_course_card){
	$attrs = array();
	
	if($tee == 'gold' || $tee == 'black') {
		$attrs['distance'] = $golf_course_card->gold_tee_distance;
		$attrs['tee_x'] = $golf_course_card->gold_tee_x;
		$attrs['tee_y'] = $golf_course_card->gold_tee_y;
	} else if($tee == 'blue') {
		$attrs['distance'] = $golf_course_card->blue_tee_distance;
		$attrs['tee_x'] = $golf_course_card->blue_tee_x;
		$attrs['tee_y'] = $golf_course_card->blue_tee_y;
	} else if($tee == 'white') {
		$attrs['distance'] = $golf_course_card->white_tee_distance;
		$attrs['tee_x'] = $golf_course_card->white_tee_x;
		$attrs['tee_y'] = $golf_course_card->white_tee_y;
	} else if($tee == 'red') {
		$attrs['distance'] = $golf_course_card->red_tee_distance;
		$attrs['tee_x'] = $golf_course_card->red_tee_x;
		$attrs['tee_y'] = $golf_course_card->red_tee_y;
	}
	return $attrs;
}
function save_golf_course_card1($golf_course_card_id,$golf_course_id,$hole,$map) {
	global $CONFIG;
	// 	if ($type == "") {
	// 		throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet'));
	// 	}
	if($golf_course_card_id) {
		return update_data("UPDATE {$CONFIG->dbprefix}golf_course_card
		SET map = '$map' WHERE golf_course_card_id = $golf_course_card_id");
	} else {
		return insert_data("INSERT INTO {$CONFIG->dbprefix}golf_course_card
		(golf_course_id, hole, map)	VALUES ($golf_course_id, $hole, '$map')");
	}
}
function save_golf_course_card($golf_course_card) {
	global $CONFIG;
	if($golf_course_card->golf_course_card_id) {
		$conditon = "";
		if($golf_course_card->gold_tee_distance) {
			$conditon = $conditon . "gold_tee_distance = $golf_course_card->gold_tee_distance,";
		}
		if($golf_course_card->blue_tee_distance) {
			$conditon = $conditon . "blue_tee_distance = $golf_course_card->blue_tee_distance,";
		}
		if($golf_course_card->white_tee_distance) {
			$conditon = $conditon . "white_tee_distance = $golf_course_card->white_tee_distance,";
		}
		if($golf_course_card->red_tee_distance) {
			$conditon = $conditon . "red_tee_distance = $golf_course_card->red_tee_distance,";
		}
		if($golf_course_card->par) {
			$conditon = $conditon . "par = $golf_course_card->par,";
		}
		if($golf_course_card->hole_x) {
			$conditon = $conditon . "hole_x = $golf_course_card->hole_x,";
		}
		if($golf_course_card->hole_y) {
			$conditon = $conditon . "hole_y = $golf_course_card->hole_y,";
		}
		if($golf_course_card->gold_tee_x) {
			$conditon = $conditon . "gold_tee_x = $golf_course_card->gold_tee_x,";
		}
		if($golf_course_card->gold_tee_y) {
			$conditon = $conditon . "gold_tee_y = $golf_course_card->gold_tee_y,";
		}
		if($golf_course_card->blue_tee_x) {
			$conditon = $conditon . "blue_tee_x = $golf_course_card->blue_tee_x,";
		}
		if($golf_course_card->blue_tee_y) {
			$conditon = $conditon . "blue_tee_y = $golf_course_card->blue_tee_y,";
		}
		if($golf_course_card->white_tee_x) {
			$conditon = $conditon . "white_tee_x = $golf_course_card->white_tee_x,";
		}
		if($golf_course_card->white_tee_y) {
			$conditon = $conditon . "white_tee_y = $golf_course_card->white_tee_y,";
		}
		if($golf_course_card->red_tee_x) {
			$conditon = $conditon . "red_tee_x = $golf_course_card->red_tee_x,";
		}
		if($golf_course_card->red_tee_x) {
			$conditon = $conditon . "red_tee_y = $golf_course_card->red_tee_y,";
		}
		if($golf_course_card->map) {
			$conditon = $conditon . "map = '$golf_course_card->map',";
		}
		if(strlen($conditon) > 0) {
			$conditon = substr($conditon, 0, strlen($conditon) - 1);
		}
		return update_data("UPDATE {$CONFIG->dbprefix}golf_course_card
			SET $conditon 
			WHERE golf_course_card_id = $golf_course_card->golf_course_card_id");
	} else {
		return insert_data("INSERT INTO {$CONFIG->dbprefix}golf_course_card
		(golf_course_id, hole, map)	VALUES ($golf_course_card->golf_course_id, $golf_course_card->hole, '$golf_course_card->map')");
	}
}
function save_golf_course($golf_course) {
	global $CONFIG;
	$conditon1 = "";
	$conditon2 = "";
	$conditon = "";
	if($golf_course->course_name) {
		$conditon = $conditon . "course_name = '$golf_course->course_name',";
		$conditon1 = $conditon1 . "course_name,";
		$conditon2 = $conditon2 . "'$golf_course->course_name',";
	}
	if($golf_course->par_total) {
		$conditon = $conditon . "par_total = $golf_course->par_total,";
		$conditon1 = $conditon1 . "par_total,";
		$conditon2 = $conditon2 . "$golf_course->par_total,";
	}
	if($golf_course->gold_tee_name) {
		$conditon = $conditon . "gold_tee_name = '$golf_course->gold_tee_name',";
		$conditon1 = $conditon1 . "gold_tee_name,";
		$conditon2 = $conditon2 . "'$golf_course->gold_tee_name',";
	}
	if($golf_course->gold_course_rating) {
		$conditon = $conditon . "gold_course_rating = $golf_course->gold_course_rating,";
		$conditon1 = $conditon1 . "gold_course_rating,";
		$conditon2 = $conditon2 . "$golf_course->gold_course_rating,";
	}
	if($golf_course->gold_course_slope) {
		$conditon = $conditon . "gold_course_slope = $golf_course->gold_course_slope,";
		$conditon1 = $conditon1 . "gold_course_slope,";
		$conditon2 = $conditon2 . "$golf_course->gold_course_slope,";
	}
	if($golf_course->gold_total) {
		$conditon = $conditon . "gold_total = $golf_course->gold_total,";
		$conditon1 = $conditon1 . "gold_total,";
		$conditon2 = $conditon2 . "$golf_course->gold_total,";
	}
	if($golf_course->blue_tee_name) {
		$conditon = $conditon . "blue_tee_name = '$golf_course->blue_tee_name',";
		$conditon1 = $conditon1 . "blue_tee_name,";
		$conditon2 = $conditon2 . "'$golf_course->blue_tee_name',";
	}
	if($golf_course->blue_course_rating) {
		$conditon = $conditon . "blue_course_rating = $golf_course->blue_course_rating,";
		$conditon1 = $conditon1 . "blue_course_rating,";
		$conditon2 = $conditon2 . "$golf_course->blue_course_rating,";
	}
	if($golf_course->blue_course_slope) {
		$conditon = $conditon . "blue_course_slope = $golf_course->blue_course_slope,";
		$conditon1 = $conditon1 . "blue_course_slope,";
		$conditon2 = $conditon2 . "$golf_course->blue_course_slope,";
	}
	if($golf_course->blue_total) {
		$conditon = $conditon . "blue_total = $golf_course->blue_total,";
		$conditon1 = $conditon1 . "blue_total,";
		$conditon2 = $conditon2 . "$golf_course->blue_total,";
	}
	if($golf_course->white_tee_name) {
		$conditon = $conditon . "white_tee_name = '$golf_course->white_tee_name',";
		$conditon1 = $conditon1 . "white_tee_name,";
		$conditon2 = $conditon2 . "'$golf_course->white_tee_name',";
	}
	if($golf_course->white_course_rating) {
		$conditon = $conditon . "white_course_rating = $golf_course->white_course_rating,";
		$conditon1 = $conditon1 . "white_course_rating,";
		$conditon2 = $conditon2 . "$golf_course->white_course_rating,";
	}
	if($golf_course->white_course_slope) {
		$conditon = $conditon . "white_course_slope = $golf_course->white_course_slope,";
		$conditon1 = $conditon1 . "white_course_slope,";
		$conditon2 = $conditon2 . "$golf_course->white_course_slope,";
	}
	if($golf_course->white_total) {
		$conditon = $conditon . "white_total = $golf_course->white_total,";
		$conditon1 = $conditon1 . "white_total,";
		$conditon2 = $conditon2 . "$golf_course->white_total,";
	}
	if($golf_course->red_tee_name) {
		$conditon = $conditon . "red_tee_name = '$golf_course->red_tee_name',";
		$conditon1 = $conditon1 . "red_tee_name,";
		$conditon2 = $conditon2 . "'$golf_course->red_tee_name',";
	}
	if($golf_course->red_course_rating) {
		$conditon = $conditon . "red_course_rating = $golf_course->red_course_rating,";
		$conditon1 = $conditon1 . "red_course_rating,";
		$conditon2 = $conditon2 . "$golf_course->red_course_rating,";
	}
	if($golf_course->red_course_slope) {
		$conditon = $conditon . "red_course_slope = $golf_course->red_course_slope,";
		$conditon1 = $conditon1 . "red_course_slope,";
		$conditon2 = $conditon2 . "$golf_course->red_course_slope,";
	}
	if($golf_course->red_total) {
		$conditon = $conditon . "red_total = $golf_course->red_total,";
		$conditon1 = $conditon1 . "red_total,";
		$conditon2 = $conditon2 . "$golf_course->red_total,";
	}
	if(strlen($conditon) > 0) {
		$conditon = substr($conditon, 0, strlen($conditon) - 1);
		$conditon1 = substr($conditon1, 0, strlen($conditon1) - 1);
		$conditon2 = substr($conditon2, 0, strlen($conditon2) - 1);
	}
	if($golf_course->golf_course_id) {
		return update_data("UPDATE {$CONFIG->dbprefix}golf_course
		SET $conditon
		WHERE golf_course_id = $golf_course->golf_course_id");
	} else {
		return insert_data("INSERT INTO {$CONFIG->dbprefix}golf_course
		($conditon1) VALUES ($conditon2)");
	}
	}